<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/7/4
 * Time: 10:50
 */

namespace backend\controllers;


use app\models\Application;
use app\models\Configuration;
use app\models\PaymentChannel;
use app\models\WxMerchants;
use common\libs\AdminInfo;
use common\libs\Tools;
use yii\web\Controller;
use Yii;

/*** 支付服务
 * Class PayServiceController
 * @package backend\controllers
 */
class PayServiceController extends BasicController
{
    // 判断Token是否正确
    public function beforeAction($action)
    {
        $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
        $allow_origin = array(
            'http://10.9.87.28:8080',
            'https://edu.jhscco.com',
            'https://edutest.jhscco.com'
        );
        // P($origin);
        if(in_array($origin, $allow_origin)){
            header('Access-Control-Allow-Origin:'.$origin);
            header('Access-Control-Allow-Methods:POST,GET');
            header('Access-Control-Allow-Credentials:true');
        }


//        if (Yii::$app->request->isPost){
//           $post = Yii::$app->request->post();
//           $access_token = isset($post['access_token'])?$post['access_token']:'';
//           $info = json_decode(Tools::Decryption($access_token),true);
//           $app_id = 1;
//           if ($info['app_id'] == $app_id){
//               return true;
//           }
//            return false;
//        }
//        $get = Yii::$app->request->get();
//        $access_token = isset($get['access_token'])?$get['access_token']:'';
//        $info = json_decode(Tools::Decryption($access_token),true);
//        $app_id = 1;
//        if ($info['app_id'] == $app_id){
//        }
        return true;

    }


    /*** 获取已开通的支付服务
     * @return false|string
     */
    public function actionHaveOpened()
    {
        $get = Yii::$app->request->get();
        if  (!isset($get['aid']) || empty($get['aid'])){
            return Tools::showRes(99,'支付应用id不能为空');
        }
        if (isset($get['appId']) and !empty($get['appId'])){
            $get['app_id'] = $this->getAppId($get['appId']);
        }else{
            return Tools::showRes(99,'参数有误');
        }



        $merchants = $get;
        $payServiceList = Configuration::find()->where('app_id = :id and aid = :aid',[':id' => $merchants['app_id'],':aid' => $merchants['aid']])->joinWith(['channel'])->select(['id','app_id','pay_configuration.cid','channel_mer_id','pay_configuration.status','pay_configuration.create_time'])->asArray()->all();
        if (!empty($payServiceList) and is_array($payServiceList)){
            foreach ($payServiceList as $key => $val){
                $val['channel_id'] = $val['channel']['channel_id'];
                $val['type'] = $val['channel']['type'];
                $val['scenario'] = $val['channel']['scenario'];
                unset($val['channel']);
                unset($val['aid']);
                $serviceList[] = $val;
            }
        }else{
            $serviceList = [];
        }

        return Tools::showRes(0,'success',[
            'serviceList' => $serviceList,
        ]);

    }

    /***未开通服务
     * @return false|string
     */
    public function actionNotOpened()
    {
        $get = Yii::$app->request->get();
        if  (!isset($get['aid']) || empty($get['aid'])){
            return Tools::showRes(99,'支付应用id不能为空');
        }
        if (isset($get['appId']) and !empty($get['appId'])){
            $get['app_id'] = $this->getAppId($get['appId']);
        }else{
            return Tools::showRes(99,'参数有误');
        }
        $merchants = $get;
        $cid = (new Configuration())->ConfigCid($merchants['aid']);
        $paymentChannel = PaymentChannel::find()->where(['not in','cid',$cid])->select(['cid','channel_id','type','status','create_time'])->asArray()->all();


        if (empty($paymentChannel)){
            $paymentChannel = [];
        }
        return Tools::showRes(0,'success',[
            'paymentChannel' => $paymentChannel,
        ]);



    }

    /*** 开通支付服务获取参数
     * @return false|string
     */
    public function actionOpenServe()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $cid = isset($post['cid'])?$post['cid']:'';
            if ( empty($cid)){
                return Tools::showRes(99,'Unauthorized');
            }

            $channelInfo= (new PaymentChannel())->gainInfo($cid);

            return Tools::showRes(0,'success',[
                'channelInfo' => $channelInfo,
            ]);
        }
    }

    /*** 修改支付服务
     * @return false|string
     */
    public function actionUpdate()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $id = isset($post['id'])?$post['id']:'';
            if (empty($id)){
                return Tools::showRes(99,'参数有误');
            }
            $openServiceInfo = Configuration::find()->where('id = :id',[':id' => $id])->joinWith(['applicte'])->asArray()->one();

            if (!empty($openServiceInfo['applicte']['channel_parameter'])){
                $channel_parameter = json_decode($openServiceInfo['applicte']['channel_parameter'],true);
                if  (!empty($openServiceInfo['configuration'])){
                    $openServiceInfo['configuration'] = json_decode($openServiceInfo['configuration'],true);
                    foreach ($channel_parameter as $key => $val){
                        foreach ($openServiceInfo['configuration'] as $k => $v){
                            if ($val['name'] == $k){
                                $channel_parameter[$key]['value'] = $v;
                            }
                        }
                    }
                }
                $openServiceInfo['channel_parameter'] = $channel_parameter;
            }
            unset($openServiceInfo['applicte'],$openServiceInfo['configuration']);

        }
        return Tools::showRes(0,'success',[
            'openServiceInfo' => $openServiceInfo,
        ]);

    }
    

    /*** 新增/修改支付服务
     * @return false|string
     */
    public function actionUpdateServe()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $configuration = isset($post['configuration'])?$post['configuration']:'';
            if (empty($configuration)){
                return Tools::showRes(99,'Unauthorized');
            }
            $configurationData =  json_decode($configuration,true);
            foreach ($configurationData as $key => $val){
                if ($val == '' and $key != 'remake' and $key != 'status'){
                    return Tools::showRes(99,$key.'不能为空');
                }
            }
            if (!isset($post['channel_mer_id']) || empty($post['channel_mer_id'])){
                return Tools::showRes(99,'渠道商户id不能为空');
            }

            if  (!isset($post['aid']) || empty($post['aid'])){
                return Tools::showRes(99,'支付应用id不能为空');
            }
            if (isset($post['appId']) and !empty($post['appId'])){
                $post['app_id'] = $this->getAppId($post['appId']);
            }else{
                return Tools::showRes(99,'参数有误');
            }

            $configModel = new Configuration();
            if ($configModel->addConfig($post)){
                return Tools::showRes(0,'提交成功');
            }else{
                if  ($configModel->hasErrors()){
                    return Tools::showRes(99,$configModel->getErrors());
                }else{
                    return Tools::showRes(99,'提交失败');
                }
            }
        }
    }
    
}